package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.api.UploadImageApi;
import com.ruoyi.jihuo.domain.JhTmTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.rmi.server.ExportException;
import java.util.*;

/**
 * @Author：LXY
 * @DATE：2025-09-14 11:33
 * @Description：图片上传处理器
 */
@Component
@Slf4j
public class Jh32ImageUploadHandler implements PriorityHandler {
    @Autowired
    private UploadImageApi uploadImageApi;
    @Override
    public int getPriority() {
        return 32;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        JSONObject data = request.getData();

        JhTmTemplate template = data.getObject("template", JhTmTemplate.class);
        String jhIsModifyPicture = template.getJhIsModifyPicture();
        List<String> mainPic = data.getObject("mainPic", List.class);
        List<String> descPicUrl = data.getObject("descPicUrl", List.class);
        Map<String, String> originColorUrlMap = data.getObject("originColorUrlMap", HashMap.class);
        try {
            Map<String, String> colorUrlMap = new HashMap<>();
            Map<String, String> descUrlMap = new HashMap<>();
            List<String> uploadMainPic = new ArrayList<>();
            List<String> uploadColorPic = new ArrayList<>();
            List<String> uploadDescPic = new ArrayList<>();
            if (StringUtils.isBlank(jhIsModifyPicture) || "0".equals(jhIsModifyPicture)) {
                    originColorUrlMap.forEach(
                            (imageName, imageUrl) -> {
                                try {
                                    String uploadImage = uploadImageApi.uploadImage(imageUrl);
                                    if (StringUtils.isNotBlank(uploadImage)) {
                                        uploadColorPic.add(uploadImage);
                                        colorUrlMap.put(imageName, uploadImage);
                                    }
                                }catch (Exception e){
                                    log.error("上传颜色图时发生异常",e);
                                }
                            }
                    );
                for (String s : mainPic) {
                    try {
                        String uploadImage = uploadImageApi.uploadLocalImage(encodeFileToBase64Binary(s));
                        if (StringUtils.isNotBlank(uploadImage)) {
                            uploadMainPic.add(uploadImage);
                        }
                    }catch (Exception e){
                        log.error("上传主图时发生异常:", e);
                        throw new RuntimeException("上传主图时发生异常"+e.getMessage());
                    }
                }

                for (String s : descPicUrl) {
                    try {
                        String uploadImage = uploadImageApi.uploadImage(s);
                        if (StringUtils.isNotBlank(uploadImage)) {
                            uploadDescPic.add(uploadImage);
                            descUrlMap.put(s, uploadImage);
                        }
                    }catch (Exception e){
                        log.error("上传描述图时发生异常:", e);
                    }
                }
                data.put("uploadMainPic", uploadMainPic);
                data.put("uploadColorPic", uploadColorPic);
                data.put("uploadDescPic", uploadDescPic);
                data.put("colorUrlMap", colorUrlMap);
                data.put("descUrlMap", descUrlMap);
            }
        }catch (Exception e){
            request.setErrorInfo("图片上传时发生异常:"+e.getMessage());
            throw new RuntimeException("图片上传时发生异常:"+e.getMessage());
        }
        return true;
    }

    /**
     * 将本地路径文件转换为BASE64
     * @param filePath
     * @return
     */
    public static String encodeFileToBase64Binary(String filePath) {
        try {
            if (StringUtils.isBlank(filePath)) {
                return null;
            }
            java.io.File file = new java.io.File(filePath);
            if (!file.exists()) {
                log.error("文件不存在");
                return null;
            }
            if (!file.isFile()) {
                log.error("不是一个文件");
                return null;
            }
            if (!file.canRead()) {
                log.error("文件不可读");
                return null;
            }
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

            // 将字节数组转换为Base64编码的字符串
            String base64Image = Base64.getEncoder().encodeToString(fileContent);
            return base64Image;
        }catch (Exception e){
            log.error("图片转base64失败:" + e.getMessage() + " filePath: " + filePath);
            throw new RuntimeException("图片转base64失败");
        }
    }
}
